package com.x.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * .
 *
 * @author o_o
 * @date 2024-06-14
 */
public class demo {

    private static final List<Channel> CONNECT_LIST = new ArrayList<>();

    public static void main(String[] args) {
        ServerBootstrap server = new ServerBootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        NioEventLoopGroup event = new NioEventLoopGroup();
        server.group(group,event); //监听事件处理
        server.channel(NioServerSocketChannel.class);
        server.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) {
                //打印的日志
                ch.pipeline().addLast(new LoggingHandler(LogLevel.ERROR));
                //http协议处理器
                ch.pipeline().addLast(new HttpServerCodec());
                //半包黏包处理器，这个处理器专门用于http非常适合。请求为最大请求长度
                ch.pipeline().addLast(new HttpObjectAggregator(65536));
                //websocket的处理器。参数为请求路径
                ch.pipeline().addLast(new WebSocketServerProtocolHandler("/daimouren"));
                //websocket核心逻辑处理器
                ch.pipeline().addLast(new SimpleChannelInboundHandler<TextWebSocketFrame>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
                        //接收消息
                        String text = msg.text();
                        //创建发送消息体
                        TextWebSocketFrame backText = new TextWebSocketFrame((text));
                        //发送消息给除了自己的所有人
                        CONNECT_LIST.forEach(channel -> {
//                            if (channel != ctx.channel()){
                            //发送消息
                            channel.writeAndFlush(backText);
                            channel.closeFuture();
//                            }
                        });
                    }

                    @Override
                    public void handlerAdded(ChannelHandlerContext ctx) {
                        //将连接添加到数组
                        CONNECT_LIST.add(ctx.channel());
                    }

                    @Override
                    public void handlerRemoved(ChannelHandlerContext ctx) {
                        //将连接提出数组
                        CONNECT_LIST.remove(ctx.channel());
                    }
                });
            }
        });
        try {
            // 端口绑定
            Channel channel = server.bind(32001).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
            event.shutdownGracefully();
        }
    }

}
